package com.example.init;

import com.example.entity.SecKillSku;
import com.example.mapper.SkuMapper;
import com.example.mapper.SpuMapper;
import com.example.entity.SecKillSpu;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * @Author 游家纨绔
 * @Description TODO redis数据初始化
 * @Create 2023-09-05 20:40:00
 */
@Component
public class InitDataRedis implements ApplicationContextAware {

	@Autowired
	private SkuMapper skuMapper;
	@Autowired
	private SpuMapper spuMapper;
	@Resource
	private RedisTemplate<String, Long> redisTemplate;

	public static Date spikeTime;

	@Override
	public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
		// 将秒杀商品信息存入到redis中
		List<SecKillSku> secKillSkus = skuMapper.selectAll();
		secKillSkus.forEach(sku -> {
			// 设置过期时间
			redisTemplate.opsForValue().set("" + sku.getId(), Long.valueOf(sku.getStock()), 3, TimeUnit.SECONDS);
		});
		// 获取商品秒杀时间
		SecKillSpu secKillSpu = spuMapper.selectOne(SecKillSpu.builder().id(1).build());
		spikeTime = secKillSpu.getSpikeTime();
	}

}
